#! /usr/bin/python
# -*- coding:  utf-8 -*-
#
# accoufer : cgi script for creating/editing an offer
# 
# Copyright S.Keim 2011
# Available under the MIT licence see the COPYING file

import accoufer
import shelve
import cgi, os 

import accerror

def run():
     # extract parameters
    form = cgi.FieldStorage()
    try:
        client = form["client"].value  # client service url
    except KeyError, ValueError:
        return error(accerror.ERR_BAD_REQUEST, "missing parameter 'client'")

    # get client reference
    clients = shelve.open(accoufer.CLIENT_PATH)
    try:
        clientref = clients[client][accoufer.CLT_REF]
        offers = shelve.open(accoufer.offerpath(clientref), 'w')
    except KeyError:
        return result([]) ## no offers for this client
  
    
    # check client
    
    err, txt = accoufer.authenticate(offers)
    if err:
        return error(err, txt)
            
    # create result 
    res = []
    if "oref" in form:
        # get a specific offer ...
        oref = form["oref"].value 
        try:
            value = offers[oref]
            res.append(value)
        except KeyError:
            pass
    else:
        for key,value in offers.iteritems():
            if key.endswith('_'):
                continue
            res.append(value)
    # filter   (TODO min,max) ..     
    users = shelve.open(accoufer.USER_PATH)
    rows = []
    for oref, svalue, min_svalue, tx, login in res:
        user = users[login]
        credits = user[accoufer.USER_CREDITS]
        if credits<svalue:
            if credits<min_svalue:
                continue
            svalue=credits
        email = user[accoufer.USER_EMAIL]
        row = "%s,%d,%d,%f,%s"%(oref, svalue, min_svalue, tx, email)
        rows.append(row)
    return result(rows)

def error(code, message):
    print "Content-Type: text/plain"
    print
    print "NOK"
    print code
    print message
        
def result(data):
    print "Content-Type: text/plain"
    print
    print "OK"
    print "\n".join(data)


if __name__=="__main__":
    run()
